package nodes.command;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import parser.ParserException;
import model.Model;
import nodes.AbstractNode;
import nodes.CloseParensNode;
import nodes.ConstantNode;
import nodes.OpenParensNode;


/**
 * Runs a command(s) a specified number of times
 */
public class RepeatC extends AbstractCommand
{
    public AbstractNode evaluate (List<AbstractNode> myArguments, Model model)
    {
        if (myArguments.size() < Integer.parseInt(resources.getString("repeat")))
        {
            throw ParserException.BAD_ARGUMENTS;
        }

        int numOfRepeats = myArguments.get(0).evaluate().getValue();
        int returnValue = 0;

        for (int i = 0; i < numOfRepeats; i++)
        {
            for (int j = 1; j < myArguments.size(); j ++ ){
                returnValue = myArguments.get(j).evaluate().getValue();
            }
        }
        return new ConstantNode(returnValue);

    }
    
    @Override
    public List<AbstractNode> setUpCommand (Queue<AbstractNode> outputQueue,String name)
    {
        List<AbstractNode> arguments = new ArrayList<AbstractNode>();
        try
        {
            while (!(outputQueue.peek() instanceof OpenParensNode)){
                arguments.add(outputQueue.poll().buildTree(outputQueue));
            }
            outputQueue.poll(); //Add OpenParensNode

            while (!(outputQueue.peek() instanceof CloseParensNode)) {
                arguments.add(outputQueue.poll().buildTree(outputQueue));
            }
            outputQueue.poll(); //Add CloseParensNode
        }
        catch (NullPointerException e)
        {
            throw ParserException.BAD_TOKEN;
        }

        return arguments;
    }   
}
